﻿package de.gameduell.framework.facebook.app.pages {
	import de.gameduell.framework.facebook.app.Controller;
	import de.gameduell.framework.facebook.app.GameData;
	import de.gameduell.framework.facebook.app.PageManager;
	import de.gameduell.framework.facebook.app.SplittestConfig;
	import de.gameduell.framework.facebook.app.popups.AlertPopup;
	import de.gameduell.framework.facebook.app.popups.PyramidBasePopup;

	import fl.transitions.easing.Bounce;
	import fl.transitions.easing.None;
	import fl.transitions.easing.Regular;

	import de.gameduell.facebook.service.gen.CatalogItem;
	import de.gameduell.facebook.service.gen.JackPotGame;
	import de.gameduell.facebook.service.gen.UserProfile;
	import de.gameduell.framework.asset.AssetEvent;
	import de.gameduell.framework.asset.BitmapAsset;
	import de.gameduell.framework.debug.Debug;
	import de.gameduell.framework.facebook.FBBaseAppLayout;
	import de.gameduell.framework.facebook.FBBaseController;
	import de.gameduell.framework.facebook.Jackpot;
	import de.gameduell.framework.facebook.Page;
	import de.gameduell.framework.facebook.communication.FacebookData;
	import de.gameduell.framework.facebook.communication.ServiceLayerCommunication;
	import de.gameduell.framework.facebook.event.InventoryEvent;
	import de.gameduell.framework.game.watch.StopWatch;
	import de.gameduell.framework.gui.animation.ChainedTween;
	import de.gameduell.framework.gui.animation.GDTween;
	import de.gameduell.framework.gui.button.Button;
	import de.gameduell.framework.gui.button.ButtonEvent;
	import de.gameduell.framework.gui.popup.Popup;
	import de.gameduell.framework.gui.util.Formatter;
	import de.gameduell.framework.queue.GDAction;
	import de.gameduell.framework.queue.PopupAction;

	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.text.TextField;

	public class JackpotPage extends Page {
		private var startJackpotGameButton:Button;
		private var pageManager:PageManager;
		private var layout:FBBaseAppLayout;
		private var transactionPopup:Popup;
		private var jackpotItem:CatalogItem;
		private var jackpotPriceLabel:TextField;
		private var jackpotBox:Sprite;
		private var highScore:TextField;
		private var miniJackpotView:Sprite;
		private var stopWatch:StopWatch;
		private var bigBox:Sprite;
		private var bigRemainingTime:TextField;
		private var playJackpotAgainButton:Button;
		private var backButton:Button;
		private var bigBoxProfileImage:Sprite;
		private var jackpotBoxProfileImage:Sprite;
		private var bigHowDoesItWorkButton:Button;
		private var howDoesItWorkButton:Button;

		public function JackpotPage(aPageManager:PageManager, anId:String) {
			super(aPageManager, anId);
			pageManager = aPageManager;
			layout = FBBaseAppLayout.getInstance();
			stopWatch = new StopWatch();
			stopWatch.endTime = Jackpot.JACKPOT_TIME;
			stopWatch.addEventListener(StopWatch.TIMER_TICK, updateRemainingTimeValues);
		}

		override protected function initPage():void {
			jackpotBox   = page.getChildByName("jackpotBox") as Sprite;
			jackpotBox.x = 513;
			jackpotBox.y = -300;
			
			bigBox = page.getChildByName("bigBox") as Sprite;
				
			miniJackpotView = page.getChildByName("miniJackpotView") as Sprite;
			startJackpotGameButton = new Button(jackpotBox.getChildByName("startJackpotGameButton") as Sprite, "startJackpotGameButton");
			startJackpotGameButton.addEventListener(ButtonEvent.CLICK, onStartJackpotGame);

			highScore = jackpotBox.getChildByName("highScore") as TextField;
			bigRemainingTime = miniJackpotView.getChildByName("remainingTime") as TextField;

			bigHowDoesItWorkButton = new Button(bigBox.getChildByName("howDoesItWorkButton") as Sprite, "howDoesItWorkButton");
			bigHowDoesItWorkButton.addEventListener(ButtonEvent.CLICK, onHelpRequested);

			howDoesItWorkButton = new Button(jackpotBox.getChildByName("howDoesItWorkButtonSmall") as Sprite, "howDoesItWorkButtonSmall");
			howDoesItWorkButton.addEventListener(ButtonEvent.CLICK, onHelpRequested);
				
			playJackpotAgainButton = new Button(bigBox.getChildByName("playJackpotAgainButton") as Sprite, "playJackpotAgainButton");
			playJackpotAgainButton.addEventListener(ButtonEvent.CLICK, onStartJackpotGame);
			backButton = new Button(bigBox.getChildByName("skipButton") as Sprite, "backToMainPage");
			backButton.addEventListener(ButtonEvent.CLICK, onBackButton);

			bigBoxProfileImage = bigBox.getChildByName("leaderProfilePicture") as Sprite;
			jackpotBoxProfileImage = jackpotBox.getChildByName("leaderProfilePicture") as Sprite;
			
			miniJackpotView.visible = false;
			bigBox.visible = false;
			page.visible = false;
			
			if(Controller.getInstance().gameData.coins != -1){
				initJackpotPage();
			}else{
				Controller.getInstance().gameData.addEventListener(GameData.APP_INIT_DONE, initJackpotPage);
			}
		}
		
		private function initJackpotPage(event:Event = null):void {
			Controller.getInstance().gameData.removeEventListener(GameData.APP_INIT_DONE, initJackpotPage);
			if(controller.featureList.isEnabled(Controller.JACKPOT_FEATURE_ID)) {
				var itemId:String = String(controller.featureList.getCatalogItemId(Controller.JACKPOT_FEATURE_ID));
				jackpotItem = controller.catalog.getItemById(itemId);

				controller.applicationData.jackpot.addEventListener(Jackpot.JACKPOT_CLOSED, onJackpotClosed);
				controller.applicationData.jackpot.addEventListener(Jackpot.RESULT_REJECTED, onResultRejected);
				controller.applicationData.jackpot.addEventListener(Jackpot.REMAINING_TIME_UPDATE, updateRemainingTime);
				controller.applicationData.jackpot.addEventListener(Jackpot.JACKPOT_LEADER_CHANGED, updateLeaderProfile);
				controller.applicationData.jackpot.addEventListener(Jackpot.JACKPOT_CHANGED, updateJackpotBox);
				
				controller.addEventListener(FBBaseController.JACKPOT_GAME_START, jackpotGameStarted);
				controller.addEventListener(FBBaseController.JACKPOT_GAME_END, queueJackpotGameEnded);
				
				miniJackpotView.visible = false;
				bigBox.visible = false;
				page.visible = false;
				
				if(jackpotItem != null) {
					localeData.setValue("jackpotPrice", String(jackpotItem.price));
					controller.applicationData.jackpot.initJackpotGame();
				} else {
					controller.facebookData.addEventListener(FacebookData.FBE_USER_BALANCE, initJackpotBox);
					updateRemainingTimeValues();
				}
			} else {
				miniJackpotView.visible = false;
				bigBox.visible = false;
				page.visible = false;
			}
		}

		private function onHelpRequested(event:Event):void {
			var poppy:PyramidBasePopup = new PyramidBasePopup("howDoesItWorkPopup", "howDoesItWorkPopup", 60000, false);
			poppy.registerButton("okButton", poppy.hide);
			poppy.show();
		}

		private function updateLeaderProfile(event:Event = null):void {
			var leader:UserProfile = controller.applicationData.jackpot.jackpotLeader;
			localeData.setValue("leaderName", leader.firstName);
			if(leader.uid == controller.facebookData.userId) {
				localeData.setValue("userLeadsJackpot", "true");
			} else {
				localeData.setValue("userLeadsJackpot", "false");
			}
			try {
				var picUrl:String = leader.image;
				var asset:BitmapAsset = new BitmapAsset("pic", picUrl);
				asset.addEventListener(AssetEvent.COMPLETE, updateLeaderProfilePicture);
				asset.addEventListener(AssetEvent.LOAD_ERROR, onPicLoadError);
				asset.load();
			}catch(e:Error) {
				onPicLoadError();
			}
		}

		private function onPicLoadError(event:AssetEvent = null):void {
			try {
				bigBoxProfileImage.removeChildAt(2);
				jackpotBoxProfileImage.removeChildAt(2);
			}catch(e:Error) {
//				Debug.trace("JackpotPage::onPicLoadError: removing sprites failed ...", Debug.WARNING);
			}
			try {
				var bitmapData:BitmapData = library.createBitmapData("fb_pic_square_fallback", 50, 50);
				bigBoxProfileImage.addChild((new Bitmap(bitmapData.clone())));
				jackpotBoxProfileImage.addChild((new Bitmap(bitmapData.clone())));
			}catch(e:Error) {
				Debug.trace("JackpotPage::onPicLoadError: default_fb_avatar not in lib ... ", Debug.WARNING);
			}
		}

		private function updateLeaderProfilePicture(event:AssetEvent):void {
			var bitmapdata:BitmapData = BitmapAsset(event.asset).bitmap.bitmapData;
			try {
				bigBoxProfileImage.removeChildAt(2);
				jackpotBoxProfileImage.removeChildAt(2);
			}catch(e:Error) {
				//				
			}
			bigBoxProfileImage.addChild(new Bitmap(bitmapdata.clone()));
			jackpotBoxProfileImage.addChild(new Bitmap(bitmapdata.clone()));
		}

		private function updateRemainingTime(event:Event):void {
			var stopWatchSeconds:Number = Math.round(stopWatch.remainingTime / 1000);
			var serverRemaining:Number = Math.round(controller.applicationData.jackpot.remainingTime / 1000);
			if(stopWatchSeconds != serverRemaining && controller.applicationData.jackpot.remainingTime != 0) {
				stopWatch.stop();
				stopWatch.endTime = controller.applicationData.jackpot.remainingTime;
				stopWatch.start();
				updateRemainingTimeValues();
			}
		}

		private function updateRemainingTimeValues(event:Event = null):void {
			if(controller.applicationData.jackpot.currentJackpotOpen){
				localeData.setValue("jpTimeLeft", stopWatch.remainingTimeDigital);
			}
		}

		private function onJackpotClosed(event:Event):void {
			Debug.trace("JackpotPage::onJackpotClosed", Debug.WARNING);
			bigBox.visible = false;
			showJackpotBox();
			if(controller.applicationData.jackpot.jackpot.leaderId == controller.applicationData.facebookData.userId) {
				var poppy:PyramidBasePopup = new PyramidBasePopup("generic_1_button_header_content", "youAreAJackpotWinnerPopup", 0, false);
				poppy.registerButton("okButton", poppy.hide);
				poppy.addEventListener(Popup.HIDE, controller.communication.requestUserBalance);
				new PopupAction(poppy, true);
				localeData.setValue("yourJackpotScore", "0");
			}
		}

		private function onResultRejected(event:Event):void {
			bigBox.visible = false;
			var poppy:PyramidBasePopup = new PyramidBasePopup("generic_1_button_content", "jackpotAlreadyClosedPopup", 0, false);
			poppy.registerButton("okButton", poppy.hide);
			new PopupAction(poppy, true);
			new GDAction(localeData.setValue, ["yourJackpotScore", "0"], true);
		}

		private function jackpotGameStarted(event:Event):void {
			miniJackpotView.alpha = 1;
			miniJackpotView.visible = true;
			jackpotBox.visible = false;
			bigBox.visible = false;
		}

		private function queueJackpotGameEnded(event:Event):void {
			jackpotBox.visible = false;
			miniJackpotView.visible = false;
			localeData.setValue("yourJackpotScore", Formatter.formatNumberEnglish(String(controller.lastGameResult.score)));
			new GDAction(onJackpotGameEnded, [], true);
		}

		private function onJackpotGameEnded():void {
			controller.communication.requestGetJackpotTimeLeftInSeconds(); // manuell update
			bigBox.visible = true;
		}

		private function onBackButton(event:Event):void {
			bigBox.visible = false;
			jackpotBox.visible = true;
		}

		private function initJackpotBox(event:Event):void {
			controller.facebookData.removeEventListener(FacebookData.FBE_USER_BALANCE, initJackpotBox);
			var itemId:String = String(controller.featureList.getCatalogItemId(Controller.JACKPOT_FEATURE_ID));
			jackpotItem = controller.catalog.getItemById(itemId);
			if(jackpotItem != null) {
				try {
					jackpotPriceLabel.text = jackpotItem.price + "";
					controller.applicationData.addEventListener(Jackpot.JACKPOT_CHANGED, updateJackpotBox);
				}catch(e:Error) {
					controller.applicationData.addEventListener(Jackpot.JACKPOT_CHANGED, updateJackpotBox);
				}
			}
		}

		private function updateJackpotBox(event:Event):void {
			var jackpot:JackPotGame = controller.applicationData.jackpot.jackpot;
			try {
				updateRemainingTimeValues();
				if(!page.visible) {
					page.visible = true;
					showJackpotBox();
				}
				
				if(!stopWatch.isRunning) {
					if(jackpot.leaderId != "0") { 
						// jackpot not started
						stopWatch.start();
					}
				}
			}catch(e:Error) {
				Debug.trace("JackpotPage::updateJackpotBox: " + e.getStackTrace(), Debug.ERROR);
			}
		}

		private function onStartJackpotGame(event:ButtonEvent):void {
			if(jackpotItem != null) {
				if(transactionPopup == null) {
					transactionPopup = new Popup("cashTransactionPopup", "cashTransactionPopup", 0, false);
					transactionPopup.modal = true;
					transactionPopup.blocker.setColor(0x000000, 0.25);
				}
				controller.addEventListener(FBBaseController.OUT_OF_MONEY, transactionPopup.hide);
				controller.communication.addEventListener(ServiceLayerCommunication.PURCHASE_ITEM_FAILED, onPurchaseFailed);
				controller.inventory.addEventListener(InventoryEvent.INVENTORY_ITEM_ADDED, onInventoryItemAdded);
				transactionPopup.show();
				Controller(controller).buyJackpotGame(jackpotItem);
			} else {
				new AlertPopup("featureNotAvailablePopup", 10000, false);
				Debug.trace("JackpotPage::onStartJakcpotGame: ITEM NOT FOUND IN CATALOG !!!", Debug.WARNING);
			}
		}

		private function onPurchaseFailed(event:Event):void {
			Debug.trace("JackpotPage::onPurchaseFailed", Debug.WARNING);
			controller.communication.removeEventListener(ServiceLayerCommunication.PURCHASE_ITEM_FAILED, onPurchaseFailed);
			controller.inventory.removeEventListener(InventoryEvent.INVENTORY_ITEM_ADDED, onInventoryItemAdded);
			transactionPopup.hide();
		}

		private function onInventoryItemAdded(event:InventoryEvent):void {
			Debug.trace("JackpotPage::onInventoryItemAdded", Debug.CONNECTION);
			controller.communication.removeEventListener(ServiceLayerCommunication.PURCHASE_ITEM_FAILED, onPurchaseFailed);
			if(event.itemId == 13) {
				controller.inventory.removeEventListener(InventoryEvent.INVENTORY_ITEM_ADDED, onInventoryItemAdded);
				new GDAction(pageManager.prepareGameStart, [], true);
				new GDAction(Controller(controller).startJackpotGame, [controller.ingameType, 760, 558, layout.contentPosition.x, layout.contentPosition.y], true);
			}
			transactionPopup.hide();
		}

		private function showJackpotBox(event:Event = null):void {
			var guiPos:int = -55;
			jackpotBox.visible = true;
			var comby:ChainedTween = new ChainedTween();
			comby.addTween(new GDTween(jackpotBox, "y", None.easeNone, -500, -500, 1, false));
			comby.addTween(new GDTween(jackpotBox, "alpha", Regular.easeOut, 1, 0, 1, true));
			comby.addTween(new GDTween(jackpotBox, "alpha", None.easeNone, 1, 1, 1, false));
			comby.addTween(new GDTween(jackpotBox, "y", Bounce.easeOut, -300, guiPos, 0.8, true));
			comby.start();
		}
	}
}
